﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using xyjc;

namespace app
{
    public partial class Form1 : Form
    {
        public xyjc.App xyjcApp { get; set; }

        private ModifyTemplateForm modifyTemplateForm { get; set; }

        private delegate void transCallbackDeleGate(WordTransRecord record);
        private delegate void progressCallbackDeleGate(string message);

        public Form1()
        {
            InitializeComponent();

            xyjc.AppConfig config = new xyjc.AppConfig();
            config.SetDatabaseConnection(
                ConfigurationSettings.AppSettings["server"],
                ConfigurationSettings.AppSettings["database"],
                ConfigurationSettings.AppSettings["username"],
                ConfigurationSettings.AppSettings["password"]
            );
            config.SetFileSavePath(ConfigurationSettings.AppSettings["file_save_path"]);
            config.SetTemplatePath(@"Template");

            CreateConfigForm(config, false);
        }

        public void EnabledConfigButton(bool b)
        {
            configButton.Enabled = b;
        }

        public void EnabledEditTemplateButton(bool b)
        {
            EditTemplateButton.Enabled = b;
        }

        private void CreateConfigForm(AppConfig config, bool show)
        {
            Form1Config configForm = new Form1Config(config, this, (cfg) => {
                if(xyjcApp == null)
                {
                    xyjcApp = new xyjc.App(cfg);
                }
                else
                {
                    xyjcApp.ReloadConfig();
                }
                // 注册转换事件
                xyjcApp.SubscribeTrans("refreshRecordGridView", this, (record, obj) =>
                {
                    Invoke(new transCallbackDeleGate(TransCallback), new object[] { record });
                });
                xyjcApp.SubscribeProgress("refreshProgressLabel", this, (message, obj) =>
                {
                    Invoke(new progressCallbackDeleGate(ProgressCallback), new object[] { message });
                });
            });

            if(show)
            {
                configForm.ShowIt();
            }
            else
            {
                if (!configForm.SaveConfig())
                {
                    Enabled = false;
                    configForm.ShowIt();
                }
            }
        }

        private void TransCallback(WordTransRecord record)
        {
            int index = wordTransRecordsGridView.Rows.Add();
            DataGridViewRow row = wordTransRecordsGridView.Rows[index];

            row.Cells["Id"].Value = record.Id.ToString();
            row.Cells["InputPath"].Value = record.InputPath.ToString();
            row.Cells["OutputPath"].Value = record.OutputPath.ToString();
            row.Cells["JsonData"].Value = record.JsonData.ToString();
            row.Cells["DateTime"].Value = DateTimeEx.TimeStampToDateTime(record.DateTime.ToString()).ToLocalTime();
            row.Cells["Operation"].Value = "查看";
        }

        private void ProgressCallback(string message)
        {
            progressLabel.Text = message;
        }

        private void listenButton_Click(object sender, EventArgs e)
        {
            if(xyjcApp.IsListening)
            {
                xyjcApp.StopListen();
                listenButton.Text = "监听";
            }
            else
            {
                xyjcApp.StartListen();
                listenButton.Text = "停止监听";
            }
        }

        private void configButton_Click(object sender, EventArgs e)
        {
            CreateConfigForm(xyjcApp.Config, true);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(xyjcApp != null)
            {
                xyjcApp.StopListen();
            }
        }

        private void wordTransRecordsGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = this.wordTransRecordsGridView.Rows[e.RowIndex];
            string buttonText = row.Cells[e.ColumnIndex].Value.ToString();
            if(buttonText == "查看")
            {
                string outputPath = row.Cells["OutputPath"].Value.ToString();

                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.Arguments = string.Format("/c \"{0}{1}\"", xyjcApp.rootPath, outputPath);
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                
                try
                {
                    p.Start();
                }
                catch(Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
        }

        private void selectInputFileButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*doc*)|*.doc*"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                //try
                //{
                xyjcApp.TransWord(fileDialog.FileName);
                //}
                //catch (Exception err)
                //{
                //    MessageBox.Show(err.Message);
                //}
            }
        }

        private void EditTemplateButton_Click(object sender, EventArgs e)
        {
            ModifyTemplateForm temp = new ModifyTemplateForm(this);
            temp.ShowIt();
        }
    }
}
